<?php
/**
 * Created by IntelliJ IDEA.
 * User: luwei
 * Date: 2017/8/16
 * Time: 10:11
 */

namespace app\modules\api\models\kanjia;


use app\models\KjRecord;
use app\models\KjGoods;
use app\models\KjBargain;
use app\models\KjOrder;
use app\models\KjOrderComment;
use app\models\KjOrderDetail;
use app\modules\api\models\Model;
use yii\helpers\Html;

/**
 * @property \app\models\GoodsShare $goods_share
 * @property \app\models\KjBargain $bargains
 * @property \app\models\KjRecord $record
 */

class OrderBargainForm extends Model
{
    public $cat_id;
    public $goods_id;
    public $bargain;
    public $user_id;
    public $price;
    public $store_id;
    public $createtime;
    public $bargains;
    public $record;


    public function rules()
    {
        return [
            [['cat_id', 'goods_id'], 'required'],
            [['cat_id', 'goods_id', 'user_id', 'createtime'], 'integer'],
            [['price'], 'number'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'cat_id' => '分类id',
            'goods_id' => '商品id',
            'user_id' => '用户id',
            'price' => '砍价后金额',
            'createtime' => 'Createtime',
        ];
    }

    public function save()
    {

        if (!$this->validate()){
            return $this->errorResponse;
        }
            $user_idss = \Yii::$app->user->id;
            $goods = KjGoods::findOne(['id' => $this->goods_id, 'cat_id' => $this->cat_id, 'is_delete' => 0, 'store_id' => $this->store_id]);
            $bargain = KjBargain::findOne(['goods_id' => $this->goods_id, 'cat_id' => $this->cat_id,'user_id' => $this->user_id]);
            $record = KjRecord::findOne(['bid' => $bargain['id'],'user_id' => $user_idss]);

            if (empty($goods)){
                return [
                    'code' => 1,
                    'msg' => '没有此商品',
                ];
            }
            if (time() > $goods["limit_time"]){
                return [
                    'code' => 1,
                    'msg' => '活动已结束',
                ];
            }
            if (!KjGoods::getNum($goods->id)) {
                return [
                    'code' => 1,
                    'msg' => '商品库存不足',
                ];
            }
//            if ($bargain["price"] <= $goods["lowprice"]) {
//                return [
//                    'code' => 1,
//                    'msg' => 'TA的价格已经达到了最低价，不能继续砍啦！',
//                ];
//            }
            if ($bargain["user_id"] == $user_idss) {
                return [
                    'code' => 1,
                    'msg' => '此商品您已经发起过砍价',
                ];
            }
            $bargainprice = $this->getBargainPrice($goods, $goods["price"]);
            if (empty($record)) {
                $leftPrice = $goods["price"] - $bargainprice;
                if ($leftPrice <= $goods["lowprice"]) {
                    $leftPrice = $goods["lowprice"];
                }
                $t = \Yii::$app->db->beginTransaction();
                    $bargain = new KjBargain();
                    $bargain->cat_id = $this->cat_id;
                    $bargain->goods_id = $this->goods_id;
                    $bargain->user_id = $user_idss;
                    $bargain->price = $leftPrice;
                    $bargain->createtime = time();
                    if(!$bargain->save()){
                        $t->rollBack();
                        return [
                            'code' => 1,
                            'msg' => '创建砍价失败',
                        ];
                    }
                    $record = new KjRecord();
                    $record->cat_id = $this->cat_id;
                    $record->goods_id = $this->goods_id;
                    $record->user_id = "";
                    $record->bid = $bargain->id;
                    $record->bargainprice = $bargainprice;      //砍掉的金额
                    $record->leftprice = $leftPrice;            //剩余的金额
                    $record->createtime = time();
//                    var_dump($bargain->id);
//                    die;
                    if($record->save()){
                        $t->commit();
                    }else{
                        $t->rollBack();
                        return [
                            'code' => 1,
                            'msg' => '创建砍价失败111',
                        ];

                    }
                    $data = array(
                        'bargainprice'=> $bargainprice,
                        'leftPrice'=> $leftPrice,
                        'bid'=> $bargain->id,
                        'cat_id' => $this->cat_id,
                        'goods_id' => $this->goods_id,
                    );
                    return [
                        'code' => 0,
                        'msg' => '系统砍价成功',
                        'data' => $data,
                    ];
                } else {
                    return [
                        'code' => 1,
                        'msg' => '系统已给你砍过',

                    ];
                }


    }
//    public function savehelp()
//    {
//        if (!$this->validate()){
//            return $this->errorResponse;
//        }
//            $user_idss = \Yii::$app->user->id;
//            $goods = KjGoods::findOne(['id' => $this->goods_id, 'cat_id' => $this->cat_id, 'is_delete' => 0, 'store_id' => $this->store_id]);
//            $bargain = KjBargain::findOne(['goods_id' => $this->goods_id,'cat_id' => $this->cat_id,'user_id' => $this->user_id]);
//            $record = KjRecord::findOne(['bid' => $bargain['id'],'user_id' => $user_idss]);
//
//            if (empty($goods)){
//                return [
//                    'code' => 1,
//                    'msg' => '活动删除或不存在',
//                ];
//            }
//            if (time() > $goods["limit_time"]){
//                return [
//                    'code' => 1,
//                    'msg' => '活动已结束',
//                ];
//            }
//            if (!KjGoods::getNum($goods->id)) {
//                return [
//                    'code' => 1,
//                    'msg' => '已无更多库存，无法继续帮其砍价',
//                ];
//            }
////            var_dump($bargain);
////            die;
//
//            if ($bargain["price"] <= $goods["lowprice"]) {
//                return [
//                    'code' => 1,
//                    'msg' => 'TA的价格已经达到了最低价，不能继续砍啦！',
//                ];
//            }
//            if ($bargain["user_id"] == $user_idss) {
//                return [
//                    'code' => 1,
//                    'msg' => '不能帮自己砍价哦',
//                ];
//            }
//            if ($user_idss == 0) {
//                return [
//                    'code' => 1,
//                    'msg' => '用户信息读取失败，无法参与砍价',
//                ];
//            }
//            $bargainprice = $this->getBargainPrice($goods, $bargain["price"]);
//            if (empty($record)) {
//                $leftPrice = $bargain["price"] - $bargainprice;
//                if ($leftPrice <= $goods["lowprice"]) {
//                    $leftPrice = $goods["lowprice"];
//                }
//                $bargains = KjBargain::find()
//                    ->andWhere([
//                        'cat_id' => $this->cat_id,
//                        'goods_id' => $this->goods_id,
//                        'user_id' => $this->user_id,
//                    ])->one();
//
//                if (!$bargains) {
//                    return [
//                        'code' => 1,
//                        'msg' => '此订单没有了',
//                    ];
//                }
//                $bargains->price = $leftPrice;
//                $t = \Yii::$app->db->beginTransaction();
//                if(!$bargains = $this->save()){
//                    $t->rollBack();
//                    return [
//                        'code' => 1,
//                        'msg' => '对不起，砍价失败',
//                    ];
//
//                }
//                    $record = new KjRecord();
//                    $record->cat_id = $this->cat_id;
//                    $record->goods_id = $this->goods_id;
//                    $record->user_id = $user_idss;
//                    $record->bid = $bargain['id'];
//                    $record->bargainprice = $bargainprice;      //砍掉的金额
//                    $record->leftprice = $leftPrice;            //剩余的金额
//                    $record->createtime = time();
//                    if($record->save()){
//                        $t->commit();
//                    }else{
//                        $t->rollBack();
//                        return [
//                            'code' => 1,
//                            'msg' => '对不起，砍价失败',
//                        ];
//                    }
//
//                    $data = array(
//                        'bargainprice'=> $bargainprice,
//                        'leftPrice'=> $leftPrice,
//                        'bid'=> $bargain['id'],
//                        'cat_id' => $this->cat_id,
//                        'goods_id' => $this->goods_id,
//                    );
//                    return [
//                        'code' => 0,
//                        'msg' => '朋友帮您砍价成功',
//                        'data' => $data,
//                    ];
//
//            } else {
//                return [
//                    'code' => 1,
//                    'msg' => '你已经帮朋友砍过了哦',
//
//                ];
//            }
//
//
//    }


    //根据规则计算砍下的金额
    public function getBargainPrice($activity, $BargainNowPrice)
    {

        if (empty($activity["bargain_rule"])) {
            return 0;
        }
        if ($BargainNowPrice <= $activity["lowprice"]) {
            return 0;
        }
        $bargain_rule = json_decode($activity["bargain_rule"],true);
        $bargain_price = 0;
        $inRule = false;
        foreach ($bargain_rule as $rule) {
            if ($BargainNowPrice >= $rule["rule_pice"]) {
                $bargain_price = rand($rule["rule_start"] * 10, $rule["rule_end"] * 10) / 10;
                $inRule = true;
                break;
            }
        }
        if (!$inRule) {
            $bargain_price = rand(1 * 10, 2 * 10) / 10;
        }
        return $bargain_price;
    }

}